<?php

namespace App\Service\SystemManagement;

use App\Library\Common\DateTool;
use App\Library\FeiShu\SendFs;
use App\Models\Common\ConfigModel;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Support\Facades\Cache;

class TigerConfigService
{
    public static function index(string $module = '', string $name = '', int $pageNum = 1, int $pageSize = 20)
    {
        $paginator = ConfigModel::query()
            ->when(strlen($module), function ($q) use ($module) {
                $q->where('module', $module);
            })
            ->when(strlen($name), function ($q) use ($name) {
                $q->where('name', $name);
            })
            ->orderBy('createdAt', 'desc')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
        $userIds = [];
        $paginator->map(function (ConfigModel $config) use (&$userIds) {
            $userIds[$config->createdByUid] = $config->createdByUid;
            $userIds[$config->updatedByUid] = $config->updatedByUid;
        });
        $userInfos = RmsUserService::getRmsUserInfoByUserIds($userIds)['data'] ?? [];
        $userInfos = collect($userInfos)->keyBy('id')->toArray();
        return [
            'count'      => $paginator->total(),
            'list'       => $paginator->map(function (ConfigModel $config) use ($userInfos) {
                return [
                    'id'          => $config->id,
                    'module'      => (string)$config->module,
                    'name'        => (string)$config->name,
                    'description' => (string)$config->description,
                    'type'        => (string)$config->type,
                    'value'       => (string)$config->value,
                    'createdAt'   => (string)$config->createdAt,
                    'createdBy'   => $userInfos[$config->createdByUid]['username'] ?? '-',
                    'updatedAt'   => (string)$config->updatedAt,
                    'updatedBy'   => $userInfos[$config->updatedByUid]['username'] ?? '-',
                    'public'      => $config->public,
                ];
            }),
            'pageNum'    => $pageNum,
            'pageSize'   => $pageSize,
        ];
    }

    /**
     * 所有的去重的module
     * @return array
     */
    public static function allModules()
    {
        return Cache::remember('tiger_api:system_management:tiger_config:all_modules', 60, function () {
            $r = ConfigModel::query()->selectRaw('distinct(module) as module')->pluck('module')->toArray();
            sort($r);
            return $r;
        });
    }

    public static function save(int $id, array $data, array $userInfo)
    {
        $old = [];
        $allowTypes = ['json', 'string', 'int'];
        if (!in_array($data['type'] ?? '', $allowTypes)) {
            throw new \InvalidArgumentException('类型仅限：' . implode(',', $allowTypes));
        }
        if ($id) {
            $model = ConfigModel::find($id);
            if (null === $model) {
                throw new \RuntimeException('数据不存在');
            }
            $old = $model->toArray();
        } else {
            $count = ConfigModel::query()
                ->where('name', $data['name'] ?? '')
                ->where('module', $data['module'] ?? '')
                ->count();
            if ($count) {
                throw new \RuntimeException('当前数据已存在');
            }
            $model = new ConfigModel;
            $model->createdByUid = $userInfo['id'] ?? 0;
        }
        $model->fill($data);
        $model->updatedByUid = $userInfo['id'] ?? 0;
        $model->save();

        $content = sprintf("%s\nmodule:  %s -> %s\nname:  %s -> %s\ntype:  %s -> %s\nvalue:\n%s\n↓\n%s\ndescription:\n%s\n↓\n%s\n\n操作人: %s\n操作人ID: %s",
            DateTool::prefix(), $old['module'] ?? '', $model->module, $old['name'] ?? '', $model->name,
            $old['type'] ?? '', $model->type, $old['value'] ?? '', $model->value, $old['description'] ?? '', $model->description,
            $userInfo['username'] ?? '', $userInfo['id'] ?? 0,
        );
        try {
            SendFs::newRobot(SendFs::ROBOT_AUDIT_LOG)
                ->setTitleContent($id ? '修改TigerConfig记录' : '创建TigerConfig记录', $content)
                ->send();
        } catch (\Exception $exception) {}
        return $model;
    }
}
